//
//  CJRankControllerViewController.m
//  CoJellyCartoon
//
//  Created by dllo on 16/3/30.
//  Copyright © 2016年 CJG. All rights reserved.
//

#import "CJRankControllerViewController.h"
#import "HeadCollectionViewCell.h"
#import "MainCollectionViewCell.h"
#import "SearchModel.h"
#import "CJPrePlayPageVIewController.h"
@interface CJRankControllerViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, JmupDelegate>
@property (nonatomic, strong) CJBaseCollectionView *headCollection;
@property (nonatomic, strong) CJBaseCollectionView *collection;

@property (nonatomic, strong) NSArray *headDataSource;
@property (nonatomic, strong) NSArray *headDataSourceNew;

@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSMutableArray *freshDataSource;

@property (nonatomic, strong) SearchModel *searchModel;
//@property (nonatomic, strong) SearchModel *searchM;
@property (nonatomic, strong) NSMutableArray *mutable;

@property (nonatomic, strong) id result;
@property (nonatomic, strong) NSString *path;
@property (nonatomic, strong) NSMutableDictionary *allDataDictionary;
@property (nonatomic, assign) NSInteger changeNumber;

@property (nonatomic, strong) UIView *huadongtiao;

@end

@implementation CJRankControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"fanhui"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftAction:)];
    
    if (self.quanqu) {
        self.headDataSource = @[@"番剧", @"动画", @"音乐", @"舞蹈", @"游戏", @"科技", @"娱乐", @"鬼畜", @"电影", @"电视剧", @"时尚"];
        self.path = [[NSBundle mainBundle] pathForResource:@"Rank" ofType:@"txt"];
        self.result = [NSMutableArray arrayWithContentsOfFile:self.path];
    }
    if (self.yuanchuang) {
        self.headDataSource = @[@"原创", @"全站", @"番剧"];
        self.path = [[NSBundle mainBundle] pathForResource:@"OriginalityRank" ofType:@"txt"];
        self.result = [NSMutableArray arrayWithContentsOfFile:self.path];
    }
    
    self.allDataDictionary = [NSMutableDictionary dictionary];
    
    [self creatHeadCollectionView];
    [self createCollectionView];
    [self createView];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    self.navigationController.navigationBarHidden = NO;
    
    self.navigationItem.hidesBackButton = NO;
    
}

- (void)leftAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];

}
- (void)createView {
    self.huadongtiao = [[UIView alloc] initWithFrame:CGRectMake(0, 44, ScreenWidth / 8, 2)];
    self.huadongtiao.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.huadongtiao];
    
}

- (void)creatHeadCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(ScreenWidth / 8, 44);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.headCollection = [[CJBaseCollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 44) collectionViewLayout:flowLayout];

    self.headCollection.delegate = self;
    self.headCollection.dataSource = self;
    
    [self.headCollection registerClass:[HeadCollectionViewCell class] forCellWithReuseIdentifier:@"HeadCollectionViewCellIdentifier"];
    self.headCollection.backgroundColor = [UIColor colorWithRed:247 / 255.0 green:88 / 255.0 blue:136 / 255.0 alpha:1];
    self.headCollection.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.headCollection];
    

   
    
}

- (void)createCollectionView {
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 106);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    
    self.collection = [[CJBaseCollectionView alloc] initWithFrame:CGRectMake(0, 46, ScreenWidth, ScreenHeight - 106) collectionViewLayout:flowLayout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.showsHorizontalScrollIndicator = NO;
    self.collection.bounces = NO;
    self.collection.pagingEnabled = YES;
    [self.collection registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier:@"MainCollectionViewCellIdentifier"];
    [self.view addSubview:self.collection];
    
    [self collectionViewRequest];
    
}

- (void)collectionViewRequest {
    
    self.changeNumber = self.collection.contentOffset.x / ScreenWidth;
    [WZAFNetTool GetNetWithURL:self.result[self.changeNumber] WithBody:nil headfile:nil response:WZJSON success:^(id reuslt) {
        
        if ([[_allDataDictionary allKeys] containsObject:self.result[self.changeNumber]]) {
            return;
        }else {
        
            NSArray *arr = reuslt[@"rank"][@"list"];
            self.dataSource = [NSMutableArray arrayWithCapacity:0];
            self.freshDataSource = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary * dic in arr) {
                SearchModel *search = [[SearchModel alloc] initWithDataSource:dic];
                [self.dataSource addObject:search];
            }
            
            for (int i = 0; i < 20; i++) {
                self.searchModel = [[SearchModel alloc] init];
                self.searchModel = self.dataSource[i];
                [self.freshDataSource addObject:self.searchModel];
              
            }
//            //(@"----%ld", self.freshDataSource.count);
            [_allDataDictionary setObject:_freshDataSource forKey:self.result[self.changeNumber]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.collection reloadData];
            
        });
        
        
    } failure:^(NSError *error) {
        
    }];
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.headDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    self.mutable = [NSMutableArray arrayWithArray:_allDataDictionary[_result[indexPath.item]]];
    
    if (collectionView == self.headCollection) {
        HeadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HeadCollectionViewCellIdentifier" forIndexPath:indexPath];
        cell.label.text = self.headDataSource[indexPath.row];
        return cell;
    } else {
        MainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MainCollectionViewCellIdentifier" forIndexPath:indexPath];
        cell.dataSource = self.mutable;
        cell.delegate = self;
        return cell;
    }
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == self.headCollection) {

//        if (indexPath.row == 1) {
//            self.huadongtiao.frame = CGRectMake(ScreenWidth / 8 * indexPath.row, 44, ScreenWidth / 8, 2);
//        }
//        
//        if (indexPath.row > 1) {
////            [self.collection setContentOffset:CGPointMake(indexPath.row * ScreenWidth, 0) animated:NO];
//            self.huadongtiao.frame = CGRectMake(ScreenWidth / 8 * (indexPath.row - 1), 44, ScreenWidth / 8, 2);
//            
//        }
        if (indexPath.row == 0) {
            [self.collection setContentOffset:CGPointMake(0, 0)];
            self.huadongtiao.frame = CGRectMake(0, 44, ScreenWidth / 8, 2);
        }
    [self.collection setContentOffset:CGPointMake(indexPath.row * ScreenWidth, 0) animated:NO];
    self.huadongtiao.frame = CGRectMake(ScreenWidth / 8 * (indexPath.row), 44, ScreenWidth / 8, 2);
    [self collectionViewRequest];
        
    }
}

- (void)jumpToController:(NSInteger)number {
    CJPrePlayPageVIewController *prePlay = [[CJPrePlayPageVIewController alloc] init];
    SearchModel *sea = self.mutable[number];
    prePlay.idString = sea.aid;
    prePlay.picURL = sea.pic;
    [self.navigationController pushViewController:prePlay animated:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (_headCollection == scrollView) {
        
    } else {
        
        self.huadongtiao.frame = CGRectMake(ScreenWidth / 8 * scrollView.contentOffset.x / ScreenWidth, 44, ScreenWidth / 8, 2);
        
        [self.headCollection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:scrollView.contentOffset.x / ScreenWidth inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
//        //(@"^^^%f", scrollView.contentOffset.x);
//        
//        //(@"***%f", ScreenWidth / 8 * scrollView.contentOffset.x / ScreenWidth);
    }
    [self collectionViewRequest];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
